const { Sequelize } = require('sequelize');
const mysql = require('mysql2/promise');

// 数据库配置
const dbConfig = {
    host: 'mysql-mysql.ns-e4l6njgi.svc',
    port: 3306,
    user: 'root',
    password: 'pfkjrxs4',
    database: 'nursing_home'
};

// 创建数据库的函数
async function createDatabase() {
    try {
        // 创建一个没有指定数据库的连接
        const connection = await mysql.createConnection({
            host: dbConfig.host,
            port: dbConfig.port,
            user: dbConfig.user,
            password: dbConfig.password
        });

        // 创建数据库
        await connection.query(`CREATE DATABASE IF NOT EXISTS ${dbConfig.database};`);
        console.log('数据库创建成功或已存在');
        await connection.end();
    } catch (error) {
        console.error('创建数据库失败:', error);
        throw error;
    }
}

// 创建 Sequelize 实例
const sequelize = new Sequelize(
    dbConfig.database,
    dbConfig.user,
    dbConfig.password,
    {
        host: dbConfig.host,
        port: dbConfig.port,
        dialect: 'mysql',
        logging: false, // 关闭 SQL 查询日志
        pool: {
            max: 5,
            min: 0,
            acquire: 30000,
            idle: 10000
        },
        retry: {
            max: 3 // 连接失败时重试 3 次
        }
    }
);

module.exports = { sequelize, createDatabase }; 